package org.example.component;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import lombok.extern.slf4j.Slf4j;
import org.example.config.AlipayConfig;
import org.example.config.PayUrlConfig;
import org.example.enums.BizCodeEnum;
import org.example.enums.ClientType;
import org.example.enums.ProductOrderPayTypeEnum;
import org.example.exception.BizException;
import org.example.vo.PayInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.UUID;

@Service
@Slf4j
public class AlipayStrategy implements PayStrategy {
    @Autowired
    private PayUrlConfig payUrlConfig;

    /**
     * 支付宝下单
     */
    @Override
    public String unifiedOrder(PayInfoVO payInfoVO) {
        AlipayClient alipayClient = AlipayConfig.getInstance();
        /**
         * 等等需要转化为json数据
         */
        HashMap<String, String> content = new HashMap<>();
        log.info("订单号:{}", payInfoVO.getOutTradeNo());
        content.put("out_trade_no", payInfoVO.getOutTradeNo());
        content.put("product_code", "FAST_INSTANT_TRADE_PAY");
        // 订单总金额，单位为元，精确到小数点后两位
        content.put("total_amount", payInfoVO.getPayFee().toString());
        // 商品标题/交易标题/订单标题/订单关键字等。 注意：不可使用特殊字符，如 /，=，&amp; 等。
        content.put("subject", payInfoVO.getTitle());
        // 商品描述，可空
        content.put("body", payInfoVO.getDescription());
        // 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如 1.5h，可转换为 90m。
        double timeout = Math.floor(payInfoVO.getOrderPayTimeoutMills() / 1000 * 60);
        content.put("timeout_express", Double.valueOf(timeout).intValue() + "m");
        // 订单还剩1分钟算超时不给支付
        if (timeout < 1) {
            throw new BizException(BizCodeEnum.PAY_ORDER_PAY_TIMEOUT);
        }
        // 获取端类型
        String clientType = payInfoVO.getClientType();
        String form = "";
        try {
            if (clientType.equalsIgnoreCase(ClientType.H5.name())) {
                // H5端支付(手机)
                AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
                request.setBizContent(JSON.toJSONString(content));
                request.setNotifyUrl(payUrlConfig.getCallbackUrl());
                request.setReturnUrl(payUrlConfig.getAlipaySuccessReturnUrl());
                AlipayTradeWapPayResponse response = alipayClient.pageExecute(request);
                log.info("H5响应日志: {}", response);
                if (response.isSuccess()) {
                    System.out.println("H5端支付调用成功");
                    form = response.getBody();
                } else {
                    System.out.println("H5端支付调用失败");
                }
            } else if (clientType.equalsIgnoreCase(ClientType.PC.name())) {
                // PC端支付
                AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
                request.setNotifyUrl(payUrlConfig.getCallbackUrl());
                request.setReturnUrl(payUrlConfig.getAlipaySuccessReturnUrl());
                request.setBizContent(JSON.toJSONString(content));
                AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
                log.info("PC响应日志: {}", response);
                if (response.isSuccess()) {
                    System.out.println("PC端支付调用成功");
                    form = response.getBody();
                } else {
                    System.out.println("PC端支付调用失败");
                }
            }
        } catch (AlipayApiException e) {
            log.info("订单构建表单异常:{}, payInfoVO: {}", e, payInfoVO);
        }
        return form;
    }

    @Override
    public String refund(PayInfoVO payInfoVO) {
        return PayStrategy.super.refund(payInfoVO);
    }

    /**
     * 查询支付宝订单状态
     */
    @Override
    public String queryPaySuccess(PayInfoVO payInfoVO) {
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        HashMap<String, String> content = new HashMap<>();

        //订单商户号,64位
        content.put("out_trade_no", payInfoVO.getOutTradeNo());
        request.setBizContent(JSON.toJSONString(content));

        AlipayTradeQueryResponse response = null;
        try {
            response = AlipayConfig.getInstance().execute(request);
            log.info("支付宝订单查询响应：{}", response.getBody());

        } catch (AlipayApiException e) {
            log.error("支付宝订单查询异常:{}", e);
        }

        if (response.isSuccess()) {
            log.info("支付宝订单状态查询成功:{}", payInfoVO);
            return response.getTradeStatus();
        } else {
            log.info("支付宝订单状态查询失败:{}", payInfoVO);
            return "";
        }
    }
}
